package com.mall.order.mq.delay;


import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.List;

@Component
public class DelayOrderCancelConsumer implements ApplicationContextAware {

    DefaultMQPushConsumer consumer;

    ApplicationContext applicationContext;

    @PostConstruct
    public void init() {
        consumer = new DefaultMQPushConsumer("delay_order_cancel_consumer");

        consumer.setNamesrvAddr("127.0.0.1:9876");
        consumer.setMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                //cancelOrder();
                try {
                    DelayOrderCancelConsumer bean = applicationContext.getBean(DelayOrderCancelConsumer.class);
                    bean.cancelOrder();
                } catch (BeansException e) {
                    e.printStackTrace();
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });

        try {
            consumer.subscribe("delay_order_cancel", "*");

            consumer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }

    }

    @Transactional
    public void cancelOrder() {
            //  1.  首先重消息中取出orderId
            // 2.  查询orderId对应订单状态，如果订单的状态是已支付或已取消(什么都不做)
            // 3.  如果订单的状态，还是一个初始化状态，那意味着用户还没有支付，我们就可以取消订单
            //     a. 修改订单状态为已取消
            //     b. 还原可售卖库存:  遍历被取消的订单中的订单商品条目， -lock_count, +stock_count
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
